#!/usr/bin/env python
# -*- code=utf-8 -*-

import sys
import os

from dictapi import *
import lookup

reload(sys)
sys.setdefaultencoding('utf-8') 

class StarDictAPI(DictAPI):
    def __init__(self, dict_name, dict_dir, dict_file):
        super(StarDictAPI,self).__init__(dict_name)
        #self.dicts_dir = os.path.join(os.path.dirname(__file__))
        self.dicts_dir = os.path.join(os.getcwd())
        dict_prefix = os.path.join(self.dicts_dir, dict_dir, dict_file)
        ifo_file = dict_prefix + ".ifo"
        f = file(ifo_file)
        s = f.readlines()
        wc = int(s[2].strip().split("=")[1])
        file_size = int(s[3].strip().split("=")[1])
        f.close()

        self.dict_id = lookup.create_dict(dict_prefix,file_size,wc);
        print self.dict_id

    def translate(self,word):
        self.result.lookup_word = word
        #try:
        self.result.define = lookup.lookup(self.dict_id,word)
        #except:
            #self.result.define = 'Not Found'
    def remove(self):
        lookup.remove_dict(self.dict_id)


#test
if __name__ == "__main__":
    dict_prefix = "/usr/share/stardict/dic/stardict-langdao-ec-gb-2.4.2/langdao-ec-gb"
    #dict_prefix = "./dic/stardict-langdao-ec-gb-2.4.2/langdao-ec-gb"
    if len(sys.argv) != 2:
        print "give me a word"
        sys.exit(1)
    dict = StarDictAPI("stardict", "/usr/share/stardict/dic/stardict-langdao-ec-gb-2.4.2", "langdao-ec-gb")
    dict.translate(sys.argv[1])
    print dict.result.define
    dict.remove()

